package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReporterService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReporterServiceImpl implements ReporterService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //1.计算日期
        //1.1将日期存入集合中
        ArrayList<LocalDate> dataList = new ArrayList<>();
        dataList.add(begin);
        while (!begin.equals(end)){
             begin = begin.plusDays(1);
             dataList.add(begin);
        }
        //1.2 连接日期
        String join = StringUtils.join(dataList, ",");
        //2.计算营业额
        ArrayList<Double> turnoverList = new ArrayList<>();
        //2.1 计算每天的营页额
        for (LocalDate date : dataList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //select sum(account) from orders where order_time > beginTime and order_time <endTime and status =5
            //2.2 将参数封装到map中
            Map map = new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            //2.3 数据库查营业额
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover ==null? 0.0 : turnover;
            //2.4 将营业额封装到集合中
            turnoverList.add(turnover);
        }
        //2.5 连接营业额
        String join1 = StringUtils.join(turnoverList,",");
        //3.封装数据
        TurnoverReportVO turnoverReportVO = TurnoverReportVO
                        .builder()
                        .dateList(join)
                         .turnoverList(join1)
                        .build();
        return turnoverReportVO;
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //1.计算日期
        //1.1将日期存入集合中
        ArrayList<LocalDate> dataList = new ArrayList<>();
        dataList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dataList.add(begin);
        }
        //1.2 连接日期
        String join = StringUtils.join(dataList, ",");
        //2.计算每天用户数量
        ArrayList<Integer> newUserList = new ArrayList<>();
        ArrayList<Integer> totalUserList = new ArrayList<>();
        //2.1 计算每天的用户量
        for (LocalDate date : dataList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //2.2 将参数封装到map中
            Map map = new HashMap<>();
            map.put("end",endTime);
            //2.3 查看每天的总用户量  select count(id) from user where create_time < ?
            Integer toralUser = userMapper.countByMap(map);
            //2.4 查看每天的新增用户数量 select count(id) from user where create_time < ? and create_time > ?
            map.put("begin",beginTime);
            Integer newUser = userMapper.countByMap(map);
            //2.5 将数据加入集合
            totalUserList.add(toralUser);
            newUserList.add(newUser);
        }
        //3.封装返回对象
        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(StringUtils.join(dataList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
        return userReportVO;
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //1.计算日期
        //1.1将日期存入集合中
        ArrayList<LocalDate> dataList = new ArrayList<>();
        dataList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dataList.add(begin);
        }
        //1.2 连接日期
        String join = StringUtils.join(dataList, ",");
        //2.查询每天订单数
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dataList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //2.1查询每天的订单总是
            Integer orderCount = getOrderCount(beginTime, endTime, null);
            //2.2查询每天的有效订单数
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            //2.3加入集合
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }
        //3.查询订单总数
        //3.1 查询时间区域内订单总数量
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //3.2 查询时间区域内的有效订单总数量
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //4.计算订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dataList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
        return orderReportVO;
    }
    /**
     * 根据条件统计订单数量
     */
    private Integer getOrderCount(LocalDateTime begin,LocalDateTime end,Integer status){
        Map map = new HashMap();
        map.put("begin",begin);
        map.put("end",end);
        map.put("sattus",status);
        return orderMapper.countByMap(map);
    }

    /**
     * 销量前10统计
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        //1.将日期转为localdatatime
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //2. 查询销量前10
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        //3.转换对象
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");
        String numberList = StringUtils.join(numbers, ",");
        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
        return salesTop10ReportVO;
    }

    /**
     * 导出数据
     */
    public void exportBusinessData(HttpServletResponse response) {
    //1.查询数据库，获取营业数据
        //1.1获取日期
        LocalDate dataBegin = LocalDate.now().minusDays(30);
        LocalDate dataEnd = LocalDate.now().minusDays(1);
        LocalDateTime begin = LocalDateTime.of(dataBegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dataEnd, LocalTime.MAX);
        //1.2 查询数据
            //1.2.1 查询营业额数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(begin, end);
    //2.通过POI将数据写到excel文件中
        //2.1 获取输入流
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //2.2 创建poi对象
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //2.3 填充数据
            //2.3.1 时间
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间："+dataBegin+"至"+dataEnd);
            //2.3.2 营业额数据
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
            //2.3.3 明细数据
            for (int i = 0; i < 30; i++) {
                //1.2.2 查询明细数据
                LocalDate date = dataBegin.plusDays(i);
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
    //3.通过输出流将Excel文件下载到客户端浏览器
        //3.1 获取输出流对象
            ServletOutputStream out = response.getOutputStream();
        //3.2 写出
            excel.write(out);
        //3.3 关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
